var express = require('express');
var router = express.Router();
var comData=require('../models/comData');
var v_user=require('../models/validate/user');
var v_article=require('../models/validate/article');
var model= require('../models/db/model');
var markdown = require('markdown').markdown;
var fs = require('fs');
//引入文件上传
var upload = require('../common/upload');

//获取文章提交页面
router.get('/add',v_user.checkLogin,comData.catData,function(req, res, next) {
    //获取分类数据
        res.render('articles/add',{title:'发表文章'});

});
//获取文章提交的内容
router.post('/add',v_user.checkLogin, upload.single('img'),v_article.v_add,function(req, res, next) {

  var data=req.body;
  data.user_id=req.session.user;
  if(req.file){
    data.pic=req.file.filename;
  }
  var cats=data.cat.split('-');
  data.cat_id=cats[0];
  data.cat_name=cats[1];
    Model('article').create(data,function(err,doc){
        if(err){
            req.flash('error',err);
            return res.redirect('back');
        }else{
            Model('category').update({'_id':data.cat_id},{'$inc':{'art_num':1}},function(err){
                if(!err){
                    req.flash('success','文章发表成功');
                    res.redirect('/');
                }
            });
        }
    })
});
//获取文章详情页
router.get('/details/:_id',comData.catData,comData.newData,function(req, res, next) {
    //获取分类数据
    var _id=req.params._id;
    Model('article').update({_id:_id},{'$inc':{'pv':1}},function(err,doc){});
    Model('article').findById(_id).populate('user_id').populate('comments.user').exec(function(err,doc){
        if(doc.is_md=='是'){
            doc.content=markdown.toHTML(doc.content);
        }
        res.render('articles/details',{data:doc,title:'文章详情页'});
    });

});
//获取分类列表
router.get('/lst/:cat_id',comData.catData,comData.newData,function(req, res, next) {
    //文章列表
    var pageSize=6;//每页5条数据
    var pageNum=parseInt(req.query.pageNum)?parseInt(req.query.pageNum):1;
    var query={cat_id: req.params.cat_id};
    Model('article').count(query,function(err,num) {
        var total = num;//总记录数
        var pageTotal = Math.ceil(num / pageSize);
        var currentPage = pageNum > 0 && pageNum <= pageTotal ? pageNum : pageTotal;
        Model('article').find(query).sort({addtime:-1}).skip((currentPage-1)*pageSize).limit(pageSize).populate('user_id').exec(function (err, data) {
            res.render('articles/lst', {title: '文章分类', data: data, cat_id: req.params.cat_id,pageTotal:pageTotal,currentPage:currentPage});
        });
    });
});
//获取关键字搜索列表
router.get('/search/:pageNum',comData.catData,comData.newData,function(req, res, next) {
    var pageSize=6;//每页5条数据
    var pageNum=parseInt(req.params.pageNum);
    var keyword=req.query.keyword;
    var query = {};
    if(req.query.searchBtn){
        req.session.keyword=keyword;
    }
    if(req.session.keyword){
        query['title']=new RegExp(req.session.keyword,'i');
    }
    Model('article').count(query,function(err,num){
        var total=num;//总记录数
        var pageTotal=Math.ceil(num/pageSize);
        var currentPage=pageNum>0 && pageNum<=pageTotal?pageNum:pageTotal;
        Model('article').find(query).sort({addtime:-1}).skip((currentPage-1)*pageSize).limit(pageSize).populate('user_id').exec(function(err,docs){
            docs.forEach(function(item){
                item.content=markdown.toHTML(item.content);
            });
            res.render('articles/search',{
                title:'文章搜索列表页',
                pageTotal:pageTotal,
                currentPage:currentPage,
                keyword:keyword,
                data:docs
            });
        })
    })
});
//删除文章
router.get('/del/:_id/:cat_id/:pic/:userid',v_user.editDel,function(req, res, next) {
    Model('category').update({_id:req.params.cat_id},{$inc:{art_num:-1}},function(err,doc){
        if(!err){
            Model('article').remove({_id:req.params._id},function(err){
                if(!err){
                    if(req.params.pic!=0){
                        fs.unlink('../uploads/'+req.params.pic);//删除本地图片
                    }
                    req.flash('success','删除文章成功');
                    res.redirect('/');
                }
            })
        }
    });
});
//编辑文章
router.get('/edit/:_id/:pic/:userid',comData.catData,v_user.editDel,function(req, res, next) {
    //取出数据
    Model('article').findById(req.params._id,function(err,doc){
        res.render('articles/edit',{title:'编辑文章',data:doc});
    })
});
router.post('/edit/:_id/:pic/:userid',v_user.checkLogin,v_user.editDel,v_article.v_add,upload.single('img'),function(req, res, next) {
    //取出数据
    var data=req.body;
    if(req.file){
        data.pic=req.file.filename;
    }
    var cats=data.cat.split('-');
    data.cat_id=cats[0];
    data.cat_name=cats[1];
    var conditions={_id:req.params._id};
    Model('article').update(conditions,{$set:data},function(err,doc){
        if(err){
            req.flash('error',err);
            return res.redirect('back');
        }else{
            if(req.file && req.params.pic!=0){
                fs.unlink('../uploads/'+req.params.pic);//删除本地图片
            }
            req.flash('success','文章修改成功');
            res.redirect('/');
        }
    })
});
//提交评论
router.post('/comment',v_user.checkLogin,function(req,res,next){
    var user=req.session.user;
    Model('article').update({_id:req.body._id},{$push:{comments:{user:user,content:req.body.content}}},function(err,result){
        if(err) {
            req.flash('error', err);
            return res.redirect('back');
        }else{
            req.flash('success','评论成功');
            res.redirect('back');
            }
    })
});
module.exports = router;
